import typescript from 'rollup-plugin-typescript2';
import screeps from 'rollup-plugin-screeps';
import copy from 'rollup-plugin-copy';
import clear from 'rollup-plugin-clear';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { visualizer } from 'rollup-plugin-visualizer';

const signature = (function () {
    return new Date().toLocaleString();
})();

const banner = `//
// ╔═══╗      ╔╗     ╔═╗            ╔╗    ╔══╗      ╔╗ 
// ║╔═╗║      ║║     ║╔╝            ║║    ║╔╗║     ╔╝╚╗
// ║╚═╝║╔══╗╔═╝║╔══╗╔╝╚╗╔╗╔══╗╔══╗╔═╝║    ║╚╝╚╗╔══╗╚╗╔╝
// ║╔╗╔╝║╔╗║║╔╗║║╔╗║╚╗╔╝╠╣║╔╗║║╔╗║╔╗║║    ║╔═╗║║╔╗║ ║║ 
// ║║║╚╗║║═╣║╚╝║║║═╣ ║║ ║║║║║║║║═╣║╚╝║    ║╚═╝║║╚╝║ ║╚╗
// ╚╝╚═╝╚══╝╚══╝╚══╝ ╚╝ ╚╝╚╝╚╝╚══╝╚══╝    ╚═══╝╚══╝ ╚═╝
// 
// Author: UndefinedCpp
// Build signature: ${signature}
//
`;

let config = undefined;
// 根据指定的目标获取对应的配置项
if (!process.env.DEST) {
    console.log("未指定目标, 代码将被编译但不会上传")
}
else {
    config = require("./.secret.json")[process.env.DEST];
    if (!config) {
        throw new Error("无效目标，请检查 secret.json 中是否包含对应配置")
    }
}

// 根据指定的配置决定是上传还是复制到文件夹
const pluginDeploy = config && config.copyPath ?
    // 复制到指定路径
    copy({
        targets: [
            {
                src: 'dist/main.js',
                dest: config.copyPath
            },
            {
                src: 'dist/main.js.map',
                dest: config.copyPath,
                rename: name => name + '.map.js',
                transform: contents => `module.exports=${contents.toString()};`
            }
        ],
        hook: 'writeBundle',
        verbose: true
    }) :
    // 更新 .map 到 .map.js 并上传
    screeps({ config, dryRun: !config })

export default {
    input: 'src/main.ts',
    output: {
        file: 'dist/main.js',
        format: 'cjs',
        sourcemap: true,
        banner
    },
    plugins: [
        // 清除上次编译成果
        clear({ targets: ["dist"] }),
        // 编译 TypeScript
        resolve(),
        commonjs(),
        typescript({ tsconfig: "./tsconfig.json" }),
        // 执行上传或者复制
        pluginDeploy,
        // 执行统计
        visualizer(),
    ],
    onwarn(warning) {
        // 跳过某些警告
        if (warning.code === 'UNUSED_EXTERNAL_IMPORT') return;
        if (warning.code === 'CIRCULAR_DEPENDENCY') return;
        // 控制台打印一切警告
        console.warn(warning.message);
    },

};

console.log(`Build signature: ${signature}`);